package app.fugema.shop.main.home.view;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import app.fugema.shop.main.goods.model.GoodsPageBean;
import app.fugema.shop.main.home.adapter.HomePageAdapter;
import app.fugema.shop.main.home.model.BannerData;
import app.fugema.shop.main.home.model.HomeData;
import app.fugema.shop.main.home.model.ImgLinkData;
import app.fugema.shop.main.setting.view.SearchActivity;
import app.fugema.shop.main.setting.view.SysMsgActivity;

import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.DensityUtil;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.MyGridLayoutManager;
import com.base.common.view.adapter.bean.HeaderBean;
import com.base.common.view.adapter.connector.BaseItemTypeInterface;
import com.base.common.view.base.BaseFragment;
import com.base.common.view.base.OnGetDataListener;
import com.base.common.viewmodel.BaseViewObserver;
import app.fugema.shop.R;
import app.fugema.shop.databinding.HomePageFramentBinding;

import app.fugema.shop.main.home.vm.MainVM;

import java.util.ArrayList;
import java.util.List;

public class HomePageFragment extends BaseFragment<HomePageFramentBinding, MainVM> implements OnGetDataListener {

    @Override
    protected HomePageFramentBinding initDataBinding(LayoutInflater inflater, ViewGroup container)
    {
        return DataBindingUtil.inflate(inflater, R.layout.home_page_frament, container, false);
    }

    private HomePageAdapter homePageAdapter;

    private LinearLayoutManager mGridLayoutMgr;

    @Override
    public void initView()
    {
        super.initView();
        //设置状态栏高度
        int statusBarH = DensityUtil.getStatusBarHeight(getActivity());
        ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) binding.statusBar.getLayoutParams();
        layoutParams.height = layoutParams.height + statusBarH;
        binding.statusBar.setLayoutParams( layoutParams );

        mGridLayoutMgr = new MyGridLayoutManager(getActivity(), 2);
        binding.rvRecyclerView.setLayoutManager(mGridLayoutMgr);
        homePageAdapter = new HomePageAdapter();
        binding.rvRecyclerView.setAdapter(homePageAdapter);
        // 跳转商品 搜索
        binding.tvSearch.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                SearchActivity.start(getActivity());
            }
        });

        // 回到 顶部 按钮
        binding.btnTop.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                binding.rvRecyclerView.post( ()->{
                    binding.rvRecyclerView.smoothScrollToPosition(0);
                } );
            }
        });
        viewUtils.setRefreshLayout(binding.rvRecyclerView, this);
        //滑动监听 控制显示 回到顶部 按钮
        binding.rvRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //屏幕高度
                int screenMeasuredHeight = DensityUtil.getScreenHeightPixels();

                //如果滚动距离大于屏幕高度，那么显示回滚，否则。。。
                if (getScollYDistance() >= (screenMeasuredHeight / 2)) {
                    binding.btnTop.setVisibility(View.VISIBLE);
                } else {
                    binding.btnTop.setVisibility(View.GONE);
                }
                //Log.d("TAG", "高度为:" + getScollYDistance());
            }
        });
        // 目前 没有及时通信   先隐藏
        binding.tvSysMsg.setVisibility(View.INVISIBLE);
        //消息
        binding.tvSysMsg.setOnClickListener(v -> {
            SysMsgActivity.start(getActivity());
        });
    }


    @Override
    public void initData()
    {
        super.initData();

        //首页数据  轮播图 活动按钮
        viewModel.getHomeData().observe(this, new BaseViewObserver<LiveDataWrapper<HomeData>>() {
            @Override
            protected void onSuccess(LiveDataWrapper<HomeData> data)
            {
                setHeadView(data.data);
            }

            @Override
            public boolean isEmptyData(LiveDataWrapper<HomeData> data)
            {
                return UIUtils.isEmpty(data.data);
            }

        });

//        viewModel.tagProdList().observe(this, new BaseViewObserver<LiveDataWrapper<ProductBean>>() {
//            @Override
//            protected void onSuccess(LiveDataWrapper<ProductBean> data) {
//                homePageAdapter.setDataList(data.data.getData().get(0).getProductDtoList());
//            }
//
//            @Override
//            public boolean isEmptyData(LiveDataWrapper<ProductBean> data) {
//                return UIUtils.isEmpty(data.data.getData());
//            }
//
//        });

        //查询 第一页
        onGetData(1);
    }


    @Override
    public void onPauseRevert()
    {
        super.onPauseRevert();
        //getGoodsCartCount();
    }

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        //getGoodsCartCount();
    }

    /**
     * 设置列表头
     * @param homeData
     */
    private void setHeadView(HomeData homeData)
    {
        BannerData bannerData = new BannerData();
        BannerData cateData = new BannerData();
        List<HomeData.DatasetBean> cateList = new ArrayList<>();
        List<HomeData.LModulesBean> modules = homeData.getLModules();
        //图片链接 对象list
        List<HomeData.LModulesBean> imgLinkModules = new ArrayList<>();

        if( modules != null && !modules.isEmpty() )
        {
            for (int i = 0; i < modules.size(); i++)
            {
                if( i == 0 )
                {
                    //第一排 为 banner
                    bannerData.setData( modules.get(0).getContent().getDataset() );
                }
                else
                {
                    HomeData.LModulesBean tempLMB = modules.get(i);
                    //LogUtil.e("tempLMB","tempLMB"+tempLMB.getType());
                    if( tempLMB.getType() >= 20 )
                    {
                        imgLinkModules.add( tempLMB );
                    }
                    else
                    {
                        if( UIUtils.isNotEmpty( modules.get(i).getContent() ) && UIUtils.isNotEmpty( modules.get(i).getContent().getDataset() ) )
                        {
                            List<HomeData.DatasetBean> tempCates =  modules.get(i).getContent().getDataset();
                            for( HomeData.DatasetBean dateBean : tempCates )
                            {
                                if( dateBean.getLinkType() != 0 )
                                {
                                    cateList.add( dateBean );
                                }
                            }
                        }
                    }
                }
            }
        }
        //banner 轮播图
        bannerData.setItemType(BaseItemTypeInterface.TYPE_HEAD);
        homePageAdapter.addHeaderView(bannerData, 0);
        // 轮播下面的类别
        cateData.setItemType(BaseItemTypeInterface.TYPE_HEAD_ONE);
        cateData.setData(cateList);
        homePageAdapter.addHeaderView(cateData, 1);
        //图片链接
        if( !imgLinkModules.isEmpty() )
        {
            ImgLinkData imgLinkData = new ImgLinkData();
            imgLinkData.setItemType(BaseItemTypeInterface.TYPE_HEAD_TWO);
            imgLinkData.setData(imgLinkModules);
            homePageAdapter.addHeaderView( imgLinkData,2 );
        }

        //  商品精选 Tag
        HeaderBean header = new HeaderBean();
        header.setItemType(BaseItemTypeInterface.TYPE_HEAD_THREE);
        homePageAdapter.addHeaderView(header, 3);
        homePageAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetData(int pn)
    {
        // 首页 商品
        viewModel.getGoodsVM().getHomeGoodsByPage(pn).observe(this, new BaseViewObserver<LiveDataWrapper<GoodsPageBean>>() {
            @Override
            protected void onSuccess(LiveDataWrapper<GoodsPageBean> data)
            {
                LogUtil.e( "HomeGoods onSuccess dataSize = " + data.data.getProduct().size() );
                //homePageAdapter.setDataList(data.data.getProduct());
                viewUtils.setDataListRefreshLayout(homePageAdapter, pn, data.data.getProduct().size(), data.data.getProduct());
            }

            @Override
            public boolean isEmptyData(LiveDataWrapper<GoodsPageBean> data) {
                LogUtil.e( "HomeGoods isEmptyData "  );
                return UIUtils.isEmpty(data.data.getProduct()) && (pn == 1 );
            }

            @Override
            protected void onEmptyLayout() {
                super.onEmptyLayout();
                LogUtil.e( "HomeGoods onEmptyLayout " );
                viewUtils.stopRefreshLayout();
            }
        });

    }


    /**
     * @属性:获取屏幕高度的方法
     * @开发者:
     * @时间:2018/8/7 14:22
     */
    public int getScollYDistance()
    {
        int position = mGridLayoutMgr.findFirstVisibleItemPosition();
        View firstVisiableChildView = mGridLayoutMgr.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }

}
